<template>
    <el-form ref="formRef" :model="formData" :inline="isinline" :size="issize" :rules="isrule" hide-required-asterisk
        :disabled="isdisable">
        <template v-for="item in fieldColums" :key="item.key">
            <el-form-item :prop="item.key" :label="item.label">
                <slot v-if="`${item.comType}` === 'slot'" :name="`${item.key}`"></slot>
                <component v-if="['el-input', 'el-select'].includes(item.comType)" :is="`${item.comType}`"
                    v-model="formData[item.key]" :placeholder="item.placeholder" :show-password="item.showpassword">
                    <template v-if="item.comType === 'el-select'">
                        <el-option v-for="opt in item.options" :key="opt.value" :value="opt.value"
                            :label="opt.label"></el-option>
                    </template>
                </component>
            </el-form-item>
        </template>
    </el-form>
</template>

<script setup lang="ts">
import { ref, watch } from "vue";
import type { FormInstance } from "element-plus";
import type { FormConfig } from "./types";

const formRef = ref<FormInstance>();
const formData = ref<any>({});


const emit = defineEmits(["submit", "reset"]);
let timer = null;

const { fieldColums, isinline, issize, isrule, isdisable } = defineProps<{
    fieldColums: Array<FormConfig>;
    isinline?: boolean;
    issize?: any;
    isrule?: any;
    isdisable?: any
}>();

const onSubmit = () => {
    formRef.value?.validate((vaild) => {
        if (vaild) {
            console.log("Submit!");
            emit("submit", formData);
        }
    });
};

const onReset = () => {
    console.log("Reset!");
    formRef.value.resetFields();
    emit("reset", {});
};

watch(() => formData.value, async () => {
    if (formData.value.college && !formData.value.major) {
        formData.value.major = "无";
    }
    if(!formData.value.college) {
        formData.value.major = ""
    }
    clearTimeout(timer);
    timer = setTimeout(() => {
        emit("submit", formData);
    }, 500);
}, { deep: true })

defineExpose({
    onSubmit,
    onReset,
    formData
});
</script>

<style scoped lang="less"></style>
